package mc.support.task.common;

import org.apache.commons.lang.time.DurationFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanNameAware;

import java.util.Date;

/**
 * Created with IntelliJ IDEA. <br/>
 * Author: Francis Yun    <br/>
 * Date: 2014-04-11  <br/>
 */
public abstract class CronTaskLoggedAdaptor extends CronTaskAdaptor implements BeanNameAware {

    private static Logger log = LoggerFactory.getLogger( CronTaskLoggedAdaptor.class );

    private String taskName;

    protected String getTaskName() {
        return taskName;
    }

    @Override
    public void setBeanName(String name) {
        this.taskName = name;
    }

    @Override
    public void run() {

        String tName = getTaskName();
        TaskLog taskLog = new TaskLog();
        taskLog.setTaskName( tName );
        taskLog.setTaskBegin( new Date() );

        long ms = System.currentTimeMillis();

        int itemCount = doTask();

        ms = System.currentTimeMillis() - ms;
        String timeCost = DurationFormatUtils.formatDuration(ms, "HH:mm:ss");
        log.info( "Task: {} is Finished! Time cost: {} ", new Object[] { tName, timeCost } );

        taskLog.setItemCount( itemCount );
        taskLog.setTimeCost( timeCost );
        taskLog.setTaskEnd( new Date() );

        saveTaskLog( taskLog );
    }

    public abstract int doTask();
    public abstract void saveTaskLog(TaskLog log);

}
